<template>
  <div class="location-picker">
    <div class="location-header">
      <van-icon name="arrow-left" @click="cancel" class="back-icon" />
      <span class="title">选择位置</span>
    </div>
    <div id="location-map" class="map-container"></div>
    <div class="location-info">
      <div class="location-coords">
        <div class="coord-row">
          <div class="coord-item">
            <van-icon name="location-o" class="coord-icon" />
            <div class="coord-value">
              <span class="label">经度</span>
              <span class="value">{{ selectedLng }}</span>
            </div>
          </div>
          <div class="coord-item">
            <van-icon name="location-o" class="coord-icon" />
            <div class="coord-value">
              <span class="label">纬度</span>
              <span class="value">{{ selectedLat }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="location-actions">
        <van-button type="primary" block @click="confirmLocation" class="confirm-btn">
          <van-icon name="success" class="btn-icon" />
          确认位置
        </van-button>
        <van-button type="default" block @click="cancel" class="cancel-btn">
          <van-icon name="cross" class="btn-icon" />
          取消
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { showToast } from 'vant';

const props = defineProps<{
  initialLng?: number;
  initialLat?: number;
}>();

const emit = defineEmits<{
  (e: 'update', lng: number, lat: number): void;
  (e: 'cancel'): void;
}>();

const map = ref<any>(null);
const marker = ref<any>(null);
const selectedLng = ref<number>(props.initialLng || 114.3619);
const selectedLat = ref<number>(props.initialLat || 30.53860);

// 初始化地图
const initMap = () => {
  if (!window.AMap) {
    showToast('高德地图加载失败');
    return;
  }

  try {
    // 创建地图实例
    map.value = new window.AMap.Map('location-map', {
      zoom: 13,
      center: [selectedLng.value, selectedLat.value],
      resizeEnable: true,
      doubleClickZoom: true,
      scrollWheel: true,
      mapStyle: 'amap://styles/normal'
    });

    // 加载插件
    window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
      // 添加比例尺控件
      map.value.addControl(new window.AMap.Scale({
        position: 'LB'
      }));
      
      // 添加工具条控件
      map.value.addControl(new window.AMap.ToolBar({
        position: 'RB',
        liteStyle: false
      }));
    });

    // 创建标记
    const markerContent = document.createElement('div');
    markerContent.className = 'location-marker';
    markerContent.innerHTML = `
      <div class="marker-icon" style="
        width: 30px;
        height: 30px;
        background: #1989fa;
        border-radius: 50%;
        border: 3px solid white;
        box-shadow: 0 2px 8px rgba(0,0,0,0.3);
      "></div>
    `;

    marker.value = new window.AMap.Marker({
      position: [selectedLng.value, selectedLat.value],
      content: markerContent,
      draggable: true,
      animation: 'AMAP_ANIMATION_DROP',
      offset: new window.AMap.Pixel(-15, -15)
    });

    // 将标记添加到地图
    map.value.add(marker.value);

    // 监听地图点击事件
    map.value.on('click', (e: any) => {
      const { lng, lat } = e.lnglat;
      updateMarkerPosition(lng, lat);
    });

    // 监听标记拖拽事件
    marker.value.on('dragend', (e: any) => {
      const { lng, lat } = e.lnglat;
      updateMarkerPosition(lng, lat);
    });

    // 添加点击提示
    const clickTip = new window.AMap.InfoWindow({
      content: '<div style="padding: 8px; background: white; border: 1px solid #ddd; border-radius: 4px;">点击地图选择位置</div>',
      offset: new window.AMap.Pixel(0, -20),
      position: map.value.getCenter()
    });
    clickTip.open(map.value);
    
    // 3秒后自动隐藏提示
    setTimeout(() => {
      clickTip.close();
    }, 3000);

  } catch (error) {
    console.error('地图初始化失败:', error);
    showToast('地图初始化失败');
  }
};

// 更新标记位置
const updateMarkerPosition = (lng: number, lat: number) => {
  selectedLng.value = Number(lng.toFixed(6));
  selectedLat.value = Number(lat.toFixed(6));
  marker.value.setPosition([lng, lat]);
  
  // 尝试安全地添加动画效果
  try {
    // 先检查marker是否有setAnimation方法
    if (marker.value && typeof marker.value.setAnimation === 'function') {
      marker.value.setAnimation('AMAP_ANIMATION_DROP');
    } else if (window.AMap && window.AMap.Animation) {
      // 尝试使用新版API
      marker.value.setAnimation(window.AMap.Animation.BOUNCE);
    }
  } catch (error) {
    console.warn('设置标记动画失败:', error);
    // 动画失败不影响核心功能，继续执行
  }
};

// 确认位置
const confirmLocation = () => {
  emit('update', selectedLng.value, selectedLat.value);
};

// 取消
const cancel = () => {
  emit('cancel');
};

onMounted(() => {
  // 等待DOM更新完成后再初始化地图
  setTimeout(() => {
    initMap();
  }, 100);
});

onUnmounted(() => {
  if (map.value) {
    map.value.destroy();
  }
});
</script>

<style scoped>
.location-picker {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f7f8fa;
}

.location-header {
  padding: 12px 16px;
  background: white;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1;
}

.back-icon {
  font-size: 20px;
  color: #323233;
  margin-right: 8px;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.map-container {
  flex: 1;
  width: 100%;
  position: relative;
  min-height: 300px;
}

.location-info {
  padding: 16px;
  background: white;
  border-top: 1px solid #ebedf0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.location-coords {
  margin-bottom: 16px;
  background: #f7f8fa;
  border-radius: 8px;
  padding: 12px;
}

.coord-row {
  display: flex;
  gap: 16px;
}

.coord-item {
  flex: 1;
  display: flex;
  align-items: center;
  background: white;
  padding: 8px 12px;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.coord-icon {
  font-size: 18px;
  color: #1989fa;
  margin-right: 8px;
}

.coord-value {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.coord-value .label {
  font-size: 12px;
  color: #969799;
  margin-bottom: 2px;
}

.coord-value .value {
  font-size: 14px;
  color: #323233;
  font-weight: 500;
}

.location-actions {
  display: flex;
  gap: 12px;
}

.location-actions button {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
}

.confirm-btn {
  background: linear-gradient(135deg, #1989fa, #0570db);
  border: none;
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.3);
}

.cancel-btn {
  background: white;
  border: 1px solid #ebedf0;
  color: #323233;
}

.btn-icon {
  margin-right: 4px;
  font-size: 18px;
}

/* 标记点动画 */
:deep(.location-marker) {
  animation: markerPulse 2s infinite;
}

@keyframes markerPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

/* 自定义地图样式 */
:deep(.amap-logo) {
  display: none !important;
}

:deep(.amap-copyright) {
  opacity: 0.5;
}
</style> 